package com.cyj.mongodbsign.cyj.service.impl;

import com.cyj.mongodbsign.cyj.pojo.Student;
import com.cyj.mongodbsign.cyj.service.StudentService;
import com.mongodb.client.result.UpdateResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Transactional
@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    private MongoTemplate mongoTemplate;


    @Override
    public List<Student> getStudentBySign(Boolean flag) {
        return mongoTemplate.find(new Query().addCriteria(Criteria.where("status").is(flag?1:0)),Student.class,Student.getCollectionName());
    }

    @Override
    public UpdateResult studentSgin(String studentName) {
        Query query = new Query(Criteria.where("studentName").is(studentName));

        SimpleDateFormat bartDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Date date = new Date();

        Update update = new Update().set("sigTime",bartDateFormat.format(date)).set("status",1);
        /**
         * 更新查询返回结果集的第一条
         */
        UpdateResult result = mongoTemplate.updateFirst(query, update, Student.class, "students");

        return result;
    }

}
